# -*- coding: utf-8 -*-

from datetime import datetime
from pydantic import BaseModel, validator
from typing import Any, Dict

from utils.logger import logger


# 定义装饰器
def convert_id(subfixs):
    def decorator(cls):
        # 扫描类中的所有字段，检查字段名是否以 "_id" 结尾
        # logger.debug(f"---------------{cls.__name__}--------------")
        for field_name, field_type in cls.__annotations__.items():
            # logger.debug(f"---------------{field_name}--------------")
            for subfix in subfixs:
                if field_name.endswith(subfix) or field_name == "id":
                     # 动态创建 validator 方法
                    validator_func_name = f"convert_{field_name}_to_str"
                    validator_func = create_validator(field_name)
                    # 将该 validator 添加到类上
                    setattr(cls, validator_func_name, classmethod(validator_func))


                    # 为符合条件的字段添加一个 validator
                    method_name = f"convert_{field_name}"
                    # logger.debug(method_name)
                    attr_ = field_name
                    # 动态添加验证方法
                    @validator(field_name, pre=True)
                    def convert_to_str(cls, field_type):
                        # 转换为字符串，如果是 None 则赋默认值 "-1"
                        return str(field_type) if field_type is not None else "-1"

                    # 将验证方法绑定到类
                    setattr(cls, method_name, convert_to_str)
            # logger.debug(f"-----------------------------")
        return cls
    return decorator


def create_validator(field_name: str):
    """
    创建一个验证器函数，用于将值转换为字符串，若值为 None，则设为 "-1"。
    """
    def validator_func(cls, value):
        return str(value) if value is not None else "-1"
    return validator_func


@convert_id(["_user"])
class BaseModelMixin():
    id: str | None = None
    create_user: str | None = None
    create_time: datetime | None = None
    update_user: str | None = None
    update_time: datetime | None = None
    del_flag: int | None = None

    class Config:
        from_attributes = True

